import 'package:craze/common/index.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:craze/services/service_locator.dart';
import 'package:craze/services/user_service.dart';
import 'package:craze/stores/auth_store.dart';
import 'package:craze/models/user_model.dart';

class FanView extends StatefulWidget {
  const FanView({super.key});

  @override
  State<FanView> createState() => _FanViewState();
}

class _FanViewState extends State<FanView> {
  final AuthStore _authStore = getIt<AuthStore>();
  final UserService _userService = getIt<UserService>();

  List<UserModel> _fanUsers = [];
  bool _isLoading = true;
  String? _errorMessage;

  @override
  void initState() {
    super.initState();
    _loadFanUsers();
  }

  Future<void> _loadFanUsers() async {
    if (!mounted) return;

    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      if (_authStore.isLoggedIn && _authStore.currentUser != null) {
        final List<String> followerIds = _authStore.currentUser!.followerIds;
        final List<UserModel> users = [];

        for (final id in followerIds) {
          final user = _userService.getUserById(id);
          if (user != null) {
            users.add(user);
          }
        }

        if (mounted) {
          setState(() {
            _fanUsers = users;
            _isLoading = false;
          });
        }
      } else {
        setState(() {
          _errorMessage = "Please login first";
          _isLoading = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _errorMessage = "Load fan list failed: ${e.toString()}";
          _isLoading = false;
        });
      }
    }
  }

  Future<void> _followUser(UserModel user) async {
    if (!_authStore.isLoggedIn || _authStore.currentUser == null) return;

    try {
      // 检查是否已经关注
      if (_authStore.currentUser!.followingIds.contains(user.id)) {
        // 如果已关注，取消关注
        await _userService.unfollowUser(_authStore.currentUser!.id, user.id);

        if (mounted) {
          MyToast.showSuccess(context, 'Unfollow ${user.name}');
        }
      } else {
        // 如果未关注，添加关注
        await _userService.followUser(_authStore.currentUser!.id, user.id);

        if (mounted) {
          MyToast.showSuccess(context, 'Follow ${user.name}');
        }
      }

      // 刷新列表
      await _loadFanUsers();
    } catch (e) {
      if (mounted) {
        MyToast.showError(context, 'Operation failed: ${e.toString()}');
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFF0A1229),
      body: SafeArea(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 标题栏
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.h),
              child: Row(
                children: [
                  GestureDetector(
                    onTap: () => Navigator.of(context).pop(),
                    child: Icon(
                      MyIcons.iconBack,
                      color: Colors.white,
                      size: 20.sp,
                    ),
                  ),
                  Expanded(
                    child: Center(
                      child: Text(
                        'Fans',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 22.sp,
                          fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                          fontWeight: FontWeight.w400,
                          height: 1.36,
                        ),
                      ),
                    ),
                  ),
                  SizedBox(width: 20.sp),
                ],
              ),
            ),

            // 主体内容
            Expanded(
              child:
                  _isLoading
                      ? _buildLoadingView()
                      : _errorMessage != null
                      ? _buildErrorView()
                      : _fanUsers.isEmpty
                      ? _buildEmptyView()
                      : _buildFansGrid(),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildLoadingView() {
    return Center(child: CircularProgressIndicator(color: Colors.white));
  }

  Widget _buildErrorView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.error_outline, color: Colors.white, size: 60.sp),
          SizedBox(height: 16.h),
          Text(
            _errorMessage ?? 'Something went wrong',
            style: TextStyle(color: Colors.white, fontSize: 16.sp),
            textAlign: TextAlign.center,
          ),
          SizedBox(height: 24.h),
          ElevatedButton(
            onPressed: _loadFanUsers,
            style: ElevatedButton.styleFrom(
              backgroundColor: MyColors.blue,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(20.r),
              ),
            ),
            child: Text('Retry', style: TextStyle(color: Colors.white)),
          ),
        ],
      ),
    );
  }

  Widget _buildEmptyView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset(MyImages.empty, height: 120.h),
          SizedBox(height: 16.h),
          Text(
            'No fans',
            style: TextStyle(
              color: Colors.white,
              fontSize: 16.sp,
              fontFamily: GoogleFonts.inter().fontFamily,
              fontWeight: FontWeight.w500,
            ),
          ),
          SizedBox(height: 8.h),
          Text(
            'Share your diving experience to attract more fans',
            style: TextStyle(
              color: Colors.white.withAlpha(153),
              fontSize: 14.sp,
              fontFamily: GoogleFonts.inter().fontFamily,
              fontWeight: FontWeight.w400,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildFansGrid() {
    return GridView.builder(
      padding: EdgeInsets.all(16.w),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        childAspectRatio: 114 / 140,
        crossAxisSpacing: 10.w,
        mainAxisSpacing: 10.h,
      ),
      itemCount: _fanUsers.length,
      itemBuilder: (context, index) {
        return _buildFanCard(_fanUsers[index]);
      },
    );
  }

  Widget _buildFanCard(UserModel user) {
    final bool isFollowing =
        _authStore.currentUser?.followingIds.contains(user.id) ?? false;

    return GestureDetector(
      onTap: () {
        GoRouter.of(context).push(AppRouter.otherProfile);
      },
      child: Container(
        decoration: BoxDecoration(
          color: MyColors.cardDark,
          borderRadius: BorderRadius.circular(10.r),
        ),
        padding: EdgeInsets.all(8.w),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircleAvatar(
              radius: 27.r,
              backgroundImage: AssetImage(
                user.avatar.isNotEmpty ? user.avatar : MyImages.touxiang1,
              ),
            ),
            SizedBox(height: 8.h),
            Text(
              user.name,
              style: TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.w400,
                fontSize: 12.sp,
                fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
              ),
              textAlign: TextAlign.center,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
            SizedBox(height: 8.h),
            GestureDetector(
              onTap: () => _followUser(user),
              child: Container(
                width: 72.w,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(30.r),
                  color: isFollowing ? Colors.transparent : MyColors.blue,
                  border: isFollowing ? Border.all(color: Colors.white) : null,
                ),
                padding: EdgeInsets.symmetric(horizontal: 5.w, vertical: 6.h),
                child: Center(
                  child: Text(
                    isFollowing ? 'Followed' : 'Follow',
                    style: TextStyle(
                      fontSize: 12.sp,
                      color: Colors.white,
                      fontFamily: GoogleFonts.inter().fontFamily,
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
